package org.credo.thread.pool;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

public class java7pool {

	public static void main(String[] args) throws InterruptedException {
		ForkJoinPool pool=new ForkJoinPool();
		//提交可分解的PrintTask任务
		pool.submit(new PrintTask(0, 30));
		
		//关闭线程池
		pool.shutdown();
		pool.awaitTermination(2, TimeUnit.SECONDS);
	}
}

//我CPU是I5.双核四线程的CPU(虚拟四核实际双核).
//所以ForkJoinPool会启动四个线程来执行这个打印任务.
//而且不是连续打印,是因为程序将这个打印任务进行了分解.分解后并行执行任务.

//RecursiveAction,没有返回值
class PrintTask extends RecursiveAction{
	
	private static final long serialVersionUID = -7849183204551061688L;
	
	//每个"小任务"最多打印的数次 threshold 极限/临界强度
	private static final int THRESHOLD=5;
	private int start;
	private int end;
	
	//打印从start到end的任务
	public PrintTask(int start,int end){
		this.start=start;
		this.end=end;
	}
	
	@Override
	protected void compute() {
		//当end与start之间的差小于threshold时,开始打印
		if(end-start<THRESHOLD){
			System.out.println("come here!");
			for(int i=start;i<end;i++){
				System.out.println(Thread.currentThread().getName()+"的i值:"+i+"==="+"start:"+start+"   end:"+end);
			}
		}else{
			System.out.println("here it is!");
			//当end和start差大于threshold,即打印数超过threshold
			//将大任务分解成2个小任务
			int middle=(start+end)/2;
			PrintTask left=new PrintTask(start, middle);
			PrintTask right=new PrintTask(middle, end);
			left.fork();
			right.fork();
		}
	}
}